
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <string>

#include "JsonReader.h"
#include "cJSON.h"

using namespace std;

JsonReader::JsonReader() : m_loaded(false)
{
}

JsonReader::JsonReader(char* filename) : m_loaded(false)
{
	load(filename);
	m_loaded = true;
}

JsonReader::~JsonReader()
{
	unload();
}

void JsonReader::load(char* filename)
{
	unload();
	FILE *f=fopen(filename,"rb");fseek(f,0,SEEK_END);long len=ftell(f);fseek(f,0,SEEK_SET);
        m_data=(char*)malloc(len+1);fread(m_data,1,len,f);fclose(f);
	m_loaded = true;
}

void JsonReader::unload()
{
	if(m_loaded) {
		free(m_data);
		m_loaded = false;
	}
}

void JsonReader::setData(char* data)
{
	m_data = data;
	m_loaded = true;
}

char* JsonReader::getData(char request[], int index)
{
	char* result;
	try {
		cJSON *json = cJSON_Parse(m_data);
		if(!json) {
			// not json
			printf("Damaged file\n");
			return "";
		}
		string str(request);
		char* reqItem = strtok((char*)str.c_str(), " ");
		cJSON* item = cJSON_GetObjectItem(json, reqItem);
		reqItem = strtok(NULL, " ");

		while(reqItem) {
			if(!strcmp(reqItem, "###")) {
				item = cJSON_GetArrayItem(item, index);
			}
			else {
				item = cJSON_GetObjectItem(item, reqItem);
			}
			if(!item)
				return "";
			reqItem = strtok(NULL, " ");

		}
		if(item) {
			result = cJSON_Print(item);
			string tmp(result);
			if(tmp.length() > 2) {
				tmp = tmp.substr(1, tmp.length() - 2);
			}
			result = (char*)tmp.c_str();
			return result;
		} else {
			return "";
		}
	} catch(...) {
		// some error occured
		return "";
	}
}

int JsonReader::getArraySize(char request[])
{
        try {
                cJSON *json = cJSON_Parse(m_data);
                if(!json) {
                        // not json
                        printf("Damaged file\n");
                        return 0;
                }
                string str(request);
                char* reqItem = strtok((char*)str.c_str(), " ");
                cJSON* item = cJSON_GetObjectItem(json, reqItem);
                reqItem = strtok(NULL, " ");
                while(reqItem) {
                        item = cJSON_GetObjectItem(item, reqItem);
                        if(!item)
                                return 0;
                        reqItem = strtok(NULL, " ");
                }
		if(!item)
			return 0;
		int result = cJSON_GetArraySize(item);
                return result;
        } catch(...) {
                // some error occured
                return 0;
        }

	return 0;
}
